using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using WegasManagementSystem.BLL;
using WegasManagementSystem.Models;

namespace WegasManagementSystem.Forms
{
    public partial class SalaryPaymentForm : Form
    {
        private SalaryBLL _salaryBLL;
        private EmployeeBLL _employeeBLL;
        private DepartmentBLL _departmentBLL;
        private List<string> _yearMonths;

        public SalaryPaymentForm()
        {
            InitializeComponent();
            _salaryBLL = new SalaryBLL();
            _employeeBLL = new EmployeeBLL();
            _departmentBLL = new DepartmentBLL();
        }

        private void SalaryPaymentForm_Load(object sender, EventArgs e)
        {
            // 初始化年月下拉框
            LoadYearMonths();
            
            // 初始化部门下拉框
            LoadDepartments();
            
            // 设置默认年月为当前月
            string currentYearMonth = DateTime.Now.ToString("yyyy-MM");
            if (cboYearMonth.Items.Count > 0)
            {
                int index = cboYearMonth.Items.IndexOf(currentYearMonth);
                if (index >= 0)
                {
                    cboYearMonth.SelectedIndex = index;
                }
                else
                {
                    cboYearMonth.SelectedIndex = 0;
                }
            }
        }

        private void LoadYearMonths()
        {
            try
            {
                // 获取所有可用的年月
                _yearMonths = _salaryBLL.GetAvailableYearMonths();
                
                // 如果没有数据，添加当前月
                if (_yearMonths.Count == 0)
                {
                    _yearMonths.Add(DateTime.Now.ToString("yyyy-MM"));
                }
                
                // 设置数据源
                cboYearMonth.Items.Clear();
                foreach (string yearMonth in _yearMonths)
                {
                    cboYearMonth.Items.Add(yearMonth);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载年月列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadDepartments()
        {
            try
            {
                List<Department> departments = _departmentBLL.GetAllDepartments();
                
                // 添加"全部部门"选项
                Department allDept = new Department
                {
                    DeptId = 0,
                    DeptName = "全部部门"
                };
                departments.Insert(0, allDept);
                
                // 设置数据源
                cboDepartment.DataSource = departments;
                cboDepartment.DisplayMember = "DeptName";
                cboDepartment.ValueMember = "DeptId";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载部门列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            string yearMonth = cboYearMonth.SelectedItem?.ToString();
            if (string.IsNullOrEmpty(yearMonth))
            {
                MessageBox.Show("请选择年月", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            try
            {
                int deptId = Convert.ToInt32(cboDepartment.SelectedValue);
                string keyword = txtKeyword.Text.Trim();
                
                // 查询工资支付信息
                List<SalaryInfo> salaries = QuerySalaries(yearMonth, deptId, keyword);
                
                // 显示结果
                DisplaySalaries(salaries);
                
                // 统计
                CalculateSummary(salaries);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询工资信息失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private List<SalaryInfo> QuerySalaries(string yearMonth, int deptId, string keyword)
        {
            try
            {
                // 解析年月
                string[] parts = yearMonth.Split('-');
                int year = int.Parse(parts[0]);
                int month = int.Parse(parts[1]);
                
                // 获取工资信息
                List<SalaryInfo> salaries = _salaryBLL.GetSalaryByMonth(deptId, year, month);
                
                // 过滤关键字
                if (!string.IsNullOrEmpty(keyword))
                {
                    salaries = salaries.Where(s => 
                        s.EmpName.Contains(keyword) || 
                        s.EmpNumber.Contains(keyword) || 
                        s.DeptName.Contains(keyword)).ToList();
                }
                
                return salaries;
            }
            catch (Exception ex)
            {
                throw new Exception($"查询工资信息失败：{ex.Message}", ex);
            }
        }

        private void DisplaySalaries(List<SalaryInfo> salaries)
        {
            if (salaries == null || salaries.Count == 0)
            {
                dgvSalaries.DataSource = null;
                return;
            }
            
            // 构建显示数据
            var displayData = salaries.Select(s => new
            {
                员工ID = s.EmpId,
                员工编号 = s.EmpNumber,
                员工姓名 = s.EmpName,
                所属部门 = s.DeptName,
                职位 = s.Position,
                基本工资 = s.BaseSalary,
                职位津贴 = s.PositionAllowance,
                绩效奖金 = s.PerformanceBonus,
                加班费 = s.OvertimePay,
                社保 = s.SocialInsurance,
                公积金 = s.HousingFund,
                个税 = s.IncomeTax,
                缺勤扣款 = s.AbsenceDeduction,
                其他扣款 = s.OtherDeductions,
                应发金额 = s.TotalIncome,
                实发金额 = s.NetSalary,
                计算日期 = s.CalculateDate
            }).ToList();
            
            // 设置数据源
            dgvSalaries.DataSource = displayData;
            
            // 格式化金额显示
            string[] moneyColumns = { "基本工资", "职位津贴", "绩效奖金", "加班费", "社保", "公积金", "个税", "缺勤扣款", "其他扣款", "应发金额", "实发金额" };
            foreach (string col in moneyColumns)
            {
                if (dgvSalaries.Columns[col] != null)
                {
                    dgvSalaries.Columns[col].DefaultCellStyle.Format = "N2";
                    dgvSalaries.Columns[col].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                }
            }
            
            // 调整计算日期格式
            if (dgvSalaries.Columns["计算日期"] != null)
            {
                dgvSalaries.Columns["计算日期"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm";
            }
        }

        private void CalculateSummary(List<SalaryInfo> salaries)
        {
            if (salaries == null || salaries.Count == 0)
            {
                lblCount.Text = "共 0 条记录";
                lblTotalSalary.Text = "应发总额：¥0.00";
                lblNetSalary.Text = "实发总额：¥0.00";
                return;
            }
            
            // 计算统计数据
            int count = salaries.Count;
            decimal totalSalary = salaries.Sum(s => s.TotalIncome);
            decimal netSalary = salaries.Sum(s => s.NetSalary);
            
            // 显示统计数据
            lblCount.Text = $"共 {count} 条记录";
            lblTotalSalary.Text = $"应发总额：¥{totalSalary:N2}";
            lblNetSalary.Text = $"实发总额：¥{netSalary:N2}";
        }

        private void btnConfirmPayment_Click(object sender, EventArgs e)
        {
            if (dgvSalaries.Rows.Count == 0)
            {
                MessageBox.Show("没有工资信息可以确认支付", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            if (MessageBox.Show("确定要标记所有显示的工资记录为已支付状态吗？", "确认支付", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    string yearMonth = cboYearMonth.SelectedItem?.ToString();
                    int deptId = Convert.ToInt32(cboDepartment.SelectedValue);
                    
                    // 解析年月
                    string[] parts = yearMonth.Split('-');
                    int year = int.Parse(parts[0]);
                    int month = int.Parse(parts[1]);
                    
                    // 确认支付
                    bool success = _salaryBLL.ConfirmSalaryPayment(deptId, year, month);
                    
                    if (success)
                    {
                        MessageBox.Show("工资支付确认成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        
                        // 刷新数据
                        btnQuery_Click(sender, e);
                    }
                    else
                    {
                        MessageBox.Show("工资支付确认失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"确认工资支付失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            // 已移除Excel导出功能
            MessageBox.Show("Excel导出功能已禁用", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void dgvSalaries_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // 设置已支付状态的行背景色为淡绿色
            if (e.RowIndex >= 0 && dgvSalaries.Rows[e.RowIndex].Cells["支付状态"] != null)
            {
                object value = dgvSalaries.Rows[e.RowIndex].Cells["支付状态"].Value;
                if (value != null && value.ToString() == "已支付")
                {
                    dgvSalaries.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGreen;
                }
            }
        }

        private void dgvSalaries_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                try
                {
                    int empId = Convert.ToInt32(dgvSalaries.Rows[e.RowIndex].Cells["员工ID"].Value);
                    string yearMonth = cboYearMonth.SelectedItem?.ToString();
                    
                    // 获取详细工资信息
                    SalaryInfo salaryInfo = _salaryBLL.GetSalaryByEmployeeAndMonth(empId, yearMonth);
                    
                    if (salaryInfo != null)
                    {
                        // 显示详细信息
                        SalaryDetailForm detailForm = new SalaryDetailForm(salaryInfo);
                        detailForm.ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show("未找到详细工资信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"查看工资详情失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
} 